package utfpr.cp.parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.http.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import utfpr.cp.model.Predicate;
import utfpr.cp.model.PredicateDAO;
import utfpr.cp.model.PredicateType;

/**
 *
 * @author Adriano_2
 */
public class PredicateFactory {
    HashMap<String, Predicate> list = new HashMap<>();
    
    PredicateDAO dao;
    protected PredicateFactory(){
        dao = PredicateDAO.factory();
        JSONParser parser = new JSONParser();
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            URL url = classLoader.getResource("META-INF/predicates.json");
            File file = new File(url.toURI());

            JSONArray items = (JSONArray)  parser.parse(new FileReader(file));

            Iterator<JSONObject> iterator = items.iterator();
            while (iterator.hasNext()) {
                JSONObject jsonObject = iterator.next();

                String name = (String) jsonObject.get("name");
                String type = (String) jsonObject.get("type");
                String description = (String) jsonObject.get("description");
                
                Predicate p = dao.getByName(name);
                if (!p.exist()) {
                    p = new Predicate(name, PredicateType.valueOf(type), description);
                    if (!PredicateDAO.save(p, dao.getCurrentEntity())) {
                        dao = PredicateDAO.factory();
                    }
                }
            }
	} catch (FileNotFoundException e) {
	} catch (IOException e) {
	} catch (ParseException | org.json.simple.parser.ParseException | URISyntaxException e) {
	}
    }
    
    public Predicate getByName(String name) {
        if (!list.containsKey(name)) {
            //GET or CREATE
            Predicate p = dao.getByName(name);
            if (!p.exist()) {
                if (!PredicateDAO.save(p, dao.getCurrentEntity())) {
                    dao = PredicateDAO.factory();
                    return p;
                }
            }
            list.put(name, p);
        }
        return list.get(name);
    }
    
    private static PredicateFactory instance = null;
    public static PredicateFactory singleton() {
        if (instance == null) {
            instance = new PredicateFactory();
        }
        return instance;
    }
}
